package shanghaielectric.com.shanghaielectric;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import shanghaielectric.com.shanghaielectric.Communication.Comm_Modbus.Comm_Modbus;
import shanghaielectric.com.shanghaielectric.DBConfig.DB.DBHelper_config;
import shanghaielectric.com.shanghaielectric.DBConfig.DB.Model.DB_Device;
import shanghaielectric.com.shanghaielectric.DBConfig.DB.Model.DB_DeviceType;
import shanghaielectric.com.shanghaielectric.DBConfig.DB.Model.DB_Device_moubusRTU;
import shanghaielectric.com.shanghaielectric.DBConfig.DB.Model.DB_Device_moubusTCP;
import shanghaielectric.com.shanghaielectric.DBConfig.DB.Model.DB_Point;
import shanghaielectric.com.shanghaielectric.DBConfig.DB.Model.DB_Point_EnumData;
import shanghaielectric.com.shanghaielectric.DBConfig.DB.Model.DB_Point_modbus;
import shanghaielectric.com.shanghaielectric.DeviceConfigModel.Device.Device;
import shanghaielectric.com.shanghaielectric.MyEventBus.MyEventBusModel;
import shanghaielectric.com.shanghaielectric.RDBHelper.Cell;
import shanghaielectric.com.shanghaielectric.RDBHelper.Cell_show;
import shanghaielectric.com.shanghaielectric.RDBHelper.DataPushHelper.ObserverListener_UI;
import shanghaielectric.com.shanghaielectric.RDBHelper.DataPushHelper.ObserverListener_Write;
import shanghaielectric.com.shanghaielectric.RDBHelper.DataPushHelper.ObserverManager;
import shanghaielectric.com.shanghaielectric.RDBHelper.RDBHelper;

public class MainActivity extends Activity implements ObserverListener_UI, ObserverListener_Write {
    Comm_Modbus comm_modbus;
    public static final int CHANGEUI_UI = 666;
    public static final int CHANGEUI_Write = 888;
    public boolean flag = false;
    DB_DeviceType db_deviceType;
    DB_Device db_device;
    DB_Device_moubusTCP tcp;
    DB_Device_moubusRTU RTU;
    DB_Point_modbus pointmodbus;
    DB_Point point;
    DB_Point_EnumData enumdata;
    @BindView(R.id.button_send)
    Button button;
    @BindView(R.id.tv_showText)
    TextView tvShowText;
    @BindView(R.id.button_read)
    Button buttonRead;


//    Handler handler = new Handler(new Handler.Callback() {
//        @Override
//        public boolean handleMessage(Message message) {
//
//            switch (message.what) {
//                case CHANGEUI_UI:
//                    Map<Integer, Map<Integer, Cell_show>> mapMap = (Map<Integer, Map<Integer, Cell_show>>) message.obj;
//                    Cell_show cell_show = mapMap.get(1).get(1);
//
//                    tvShowText.append("READ___设备号=" + cell_show.deviceTypeID + "+点ID=" + cell_show.pointID + "+ 显示值" + cell_show.showValue + " +" + cell_show.unit + "\n");
//                    break;
//
//                case CHANGEUI_Write:
//                    Map<Integer, Map<Integer, Cell>> mapMap_w = (Map<Integer, Map<Integer, Cell>>) message.obj;
//                    Cell cell = mapMap_w.get(1).get(1);
//
////                    tvShowText.append("WRITE___设备号="+cell.deviceTypeID + "+点ID=" + cell.pointID + "+ 通信值" + ((Cell_write_modbus)cellWriteBasic).CommValue_bytes[0]+((Cell_write_modbus)cellWriteBasic).CommValue_bytes[1] + " +" + cellWriteBasic.isChanged + "\n");
//
//
//            }
//            return false;
//        }
//    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
//        Stetho.initializeWithDefaults(this);
        LitePal.initialize(getApplicationContext());
        EventBus.getDefault().register(this);
//        SQLiteDatabase db = Connector.getDatabase();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                if (DataSupport.findAll(DB_Device.class).size() == 0) {
//                    initDB();
//                    Map<Integer, Device> devices = DBHelper_config.getDBHelper_config().getDevices();
////                    Toast.makeText(getApplicationContext(), "size" + devices.size(), Toast.LENGTH_SHORT).show();
//                }
//            }
//        }).start();
        ObserverManager.getInstance().add_UI(this);
        ObserverManager.getInstance().add_write(this);
        comm_modbus = new Comm_Modbus();
    }

    private void initDB() {
        List<DB_DeviceType> db_deviceTypes = new ArrayList<>();

        db_deviceType = new DB_DeviceType();
        db_deviceType.name_dt = "SVG设备" + 1;
        db_deviceType.description_dt = "这是第" + (1) + "台设备";
        db_deviceType.factor_dt = "上海电气";
        db_deviceType.device_type_id_dt = 1;
        db_deviceType.protocol_Type_dt = EnumDataHelper.PROTOCOL_TYPE.RTU.getName();
        db_deviceTypes.add(db_deviceType);

        DataSupport.saveAll(db_deviceTypes);


        List<DB_Device> db_devices = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            db_device = new DB_Device();
            db_device.name = "SVG设备" + (i + 1);
            db_device.description = "这是第" + (i + 1) + "台设备";
            db_device.device_type_id = 1;
            db_device.device_id = i + 1;
                db_device.protocol_type = EnumDataHelper.PROTOCOL_TYPE.RTU.getName();
            db_devices.add(db_device);
        }
        DataSupport.saveAll(db_devices);
        List<DB_Device_moubusTCP> db_device_moubusTCPS = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            tcp = new DB_Device_moubusTCP();
            tcp.deviceID = i + 1;
            tcp.ipAddress = "192.168.9.98";
            tcp.port = 5555;
            tcp.slaveID = i + 1;
            db_device_moubusTCPS.add(tcp);
        }
        DataSupport.saveAll(db_device_moubusTCPS);

        List<DB_Device_moubusRTU> db_device_moubusRTUS = new ArrayList<>();

        for (int i = 0; i < 8; i++) {
            RTU = new DB_Device_moubusRTU();
            RTU.stopBits = 1;
            RTU.parityBits = "None";
            RTU.dataBits = 8;
            RTU.baudRate = 9600;
            RTU.com_ID = i + 1;
            RTU.device_ID = i + 1;
            RTU.slave_ID = i + 1;
            db_device_moubusRTUS.add(RTU);
        }

        DataSupport.saveAll(db_device_moubusRTUS);
        List<DB_Point> db_points = new ArrayList<>();
        List<DB_Point_modbus> db_point_modbuses = new ArrayList<>();

        for (int i = 0; i < 117; i++) {
            point = new DB_Point();
            point.pointID = i + 1;
            point.deviceTypeID = 1;
            point.isDisplay = 0;
            point.initValue = "";
            point.isInternal = 0;
            point.maxValue = 32768;
            point.minValue = -32768;
            point.name = "点" + i;
            point.precision = 1;
            point.protocolType = "RTU";
            point.scale = 1;
            point.type = "COMCALC";
            point.unit = "单位";
            point.isread = i < 88;

            pointmodbus = new DB_Point_modbus();
            pointmodbus.address = 4000 + i;
            pointmodbus.pointID = i + 1;
            pointmodbus.slaveID = i + 1;
            pointmodbus.type_bit = i < 88 ? EnumDataHelper.MODBUS_DATA_TYPE.READ_SHORT.getName() : EnumDataHelper.MODBUS_DATA_TYPE.READ_WRITE_SHORT.getName();

            db_points.add(point);
            db_point_modbuses.add(pointmodbus);
        }
        DataSupport.saveAll(db_points);
        DataSupport.saveAll(db_point_modbuses);

        List<DB_Point_EnumData> db_point_enumData = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            enumdata = new DB_Point_EnumData();
            enumdata.enumKey = i % 4;
            enumdata.enumValue = "枚举value" + i % 4;
            enumdata.pointID = i / 4;
            db_point_enumData.add(enumdata);
        }
        DataSupport.saveAll(db_point_enumData);
    }

    @Override
    public void update_UI(Map<Integer, Map<Integer, Cell_show>> mapMap) {
//        Toast.makeText(this, "收到数据改变通知", Toast.LENGTH_SHORT).show();
        Message message = new Message();
        message.what = CHANGEUI_UI;
        message.obj = mapMap;
//        handler.sendMessage(message);
    }

    int count = 0;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @OnClick({R.id.button_send, R.id.button_read})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.button_send:
//        Intent intent=new Intent(this,SecondActivity.class);
//        startActivity(intent);

//        EventBus.getDefault().post("这里是来自activity_1的测试请求");

                Toast.makeText(this, "点击按钮", Toast.LENGTH_SHORT).show();
                count = count + 1;
                RDBHelper rdbHelper = RDBHelper.getInstance();
//            rdbHelper.putPointValue_commValue(1, 1, 123456 + count);
//        RDBHelper.getInstance().putPointValue_writeValue(1, 1, 123456 + count+"");
//            flag = !flag;

//        rdbHelper.putPointValue_writeValue(1,89,666+"");
//                rdbHelper.putPointValue_writeValue(1, 90, "枚举value1");
//                rdbHelper.putPointValue_writeValue(7, 10, 2 + "");
//                rdbHelper.putPointValue_writeValue(7, 11, 3 + "");

                comm_modbus.sendRequest(7);

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                comm_modbus.writeData(7);
                break;
            case R.id.button_read:
                comm_modbus.readData(7);
                Log.e("read", "readData");
                break;
        }
    }

    @Override
    public void update_Write(Map<Integer, Map<Integer, Cell>> mapMap) {
        Message message = new Message();
        message.what = CHANGEUI_Write;
        message.obj = mapMap;
//        handler.sendMessage(message);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
comm_modbus.closePort();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void dealMessage(Map<Integer, Map<Integer, Cell_show>> collection) {
        Map<Integer, Cell_show> cell_showMap = new LinkedHashMap<>();
        cell_showMap = collection.get(7);
        for (Map.Entry<Integer, Cell_show> cell_show : cell_showMap.entrySet()
                ) {
            tvShowText.append("READ___设备号=" + cell_show.getValue().deviceID + "+点ID=" + cell_show.getValue().pointID + "+ 显示值" + cell_show.getValue().showValue + " +" + cell_show.getValue().unit + "\n");
        }


//        Log.e("eventbus_1","收到enevtbus数据"+string);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showToast(MyEventBusModel myEventBusModel) {
        Toast.makeText(this, myEventBusModel.exceptionObj.toString(), Toast.LENGTH_SHORT).show();
        Log.e("MainActivity", myEventBusModel.exceptionObj.toString());
    }


}
